package com.atguigu.channel;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Objects;

/**
 * className: FileChannelDemo2
 * description: FileChannelDemo2 写操作
 * date: 2023/3/8 0008-17:48
 * <p>
 * project: nio
 * package: com.atguigu.channel
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class FileChannelDemo2 {

    public static void main(String[] args) throws IOException {
        // 打开 FileChannel
        RandomAccessFile aFile = new RandomAccessFile(Objects.requireNonNull(FileChannelDemo3.class.getClassLoader().getResource("")).getPath() + "001.txt", "rw");
        FileChannel channel = aFile.getChannel();

        // 创建 buffer 对象
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        String newData = "data atguigu";
        buffer.clear();

        // 写入内容
        buffer.put(newData.getBytes());

        buffer.flip();

        // FileChannel 完成最终实现
        while (buffer.hasRemaining()) {
            channel.write(buffer);
        }

        // 关闭
        channel.close();
    }
}
